package cn.edu.nuc.onlinestore.frame;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

import cn.edu.nuc.onlinestore.Person.ObjectStream;
import cn.edu.nuc.onlinestore.model.Goods;
import cn.edu.nuc.onlinestore.network.TCPClient;

import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Vector;
import java.awt.event.ActionEvent;

public class UserStore extends JFrame {

	private JPanel contentPane;
	private JTextField textField;
	private JFrame JF;
	private static String username;
	private int buyGoodscount = 0;
    public static int totalCount=0;
	/**
	 * Launch the application.
	 *//*
		 * public static void main(String[] args) { EventQueue.invokeLater(new
		 * Runnable() { public void run() { try { UserStore frame = new
		 * UserStore(); frame.setVisible(true); } catch (Exception e) {
		 * e.printStackTrace(); } } }); }
		 */
	/**
	 * Create the frame.
	 */
    public UserStore(int totalCount){
    	this.totalCount=totalCount;
    }
    
	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
   
	public UserStore(){}
	public UserStore(String username,String str) {
		this.JF = this;
		/*this.username = username;*/
		
		File file=new File("D:/store/user/userCart/"+username);
		if(!file.isDirectory()){
			file.mkdirs();
		}
		setTitle("中北在线商场--当前用户:" + username);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 732, 467);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(10, 78, 696, 341);
		panel.setLayout(new GridLayout(1, 1, 0, 0));

		DefaultTableModel model = new DefaultTableModel();
		model.addColumn("商品编号");
		model.addColumn("名称");
		model.addColumn("单价(人民币)");
		model.addColumn("库存");
	
	
        TCPClient client=new TCPClient();
		List<Goods> listGoods=client.allGoods();
		
		
		int FileNum =listGoods.size();
   
		for (int i = 0; i < FileNum; i++) {
				
				Goods allGoods=listGoods.get(i);
				
               model.addRow(new String[] { String.valueOf(allGoods.getGid()), allGoods.getGoodsName(),
						String.valueOf(allGoods.getPrice()), String.valueOf(allGoods.getAmount()) });
			}

		JTable table = new JTable(model);

		JScrollPane pane = new JScrollPane(table);

		panel.add(pane);
		contentPane.add(panel);

		JButton button_2 = new JButton("查看商品详细信息(或双单击商品列)");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				int row = table.getSelectedRow() + 1;// 行的下标
				
				
				if(row-1==-1){
					JOptionPane.showMessageDialog(null, "未选择商品！");
				}else{
				  
					int NO=Integer.parseInt(table.getValueAt(row-1, 0).toString());
					System.out.print("您要查询商品编号："+NO+"的详情！");
					String rowValue=String.valueOf(model.getValueAt(row-1, 3));
					String msg = "GoodsDetail###"+NO;
					
					String result = new TCPClient().send(msg);
					String[] goodsInfo = result.split("###");
	
					List<String> list = new ArrayList<String>();
	
					for (int i = 0; i < goodsInfo.length; i++) {
						list.add(goodsInfo[i]);
					}
	
					UserGoods usergoods = new UserGoods(list, NO,row,model,rowValue);
					buyGoodscount = usergoods.getBuyGoodscount();
					usergoods.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
					usergoods.setVisible(true);
				}
			}
		});
		button_2.setBounds(407, 45, 299, 23);
		contentPane.add(button_2);

		JButton button_3 = new JButton("退出登录");
		button_3.setBounds(613, 6, 93, 23);
		contentPane.add(button_3);

		button_3.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				String msg = "close###";
				new TCPClient().send(msg);
				UserLogin login = new UserLogin();
				login.setVisible(true);
				JF.dispose();
			}

		});

		JLabel lblid = new JLabel("商品名称:");
		lblid.setBounds(10, 53, 65, 15);
		contentPane.add(lblid);

		textField = new JTextField();
		textField.setBounds(85, 46, 104, 21);
		contentPane.add(textField);
		textField.setColumns(10);

		JButton button_4 = new JButton("搜索");
		button_4.setBounds(197, 45, 93, 23);
		contentPane.add(button_4);

		button_4.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				//可以模糊查询，可以全查询，可以查询多个(中间以逗号隔开)
				String shopname = textField.getText();
				String msg = "search###" + shopname;
			     
				System.out.println("您要查询商品："+shopname);
			     
				HashSet<Goods> searchGoods=new TCPClient().allCartGoods(msg);
				
				model.setRowCount(0);
				for(Goods allGoods:searchGoods){
			     	
			          model.addRow(new String[] { String.valueOf(allGoods.getGid()), allGoods.getGoodsName(),String.valueOf(allGoods.getPrice()), String.valueOf(allGoods.getAmount())});
			        
			     }
				 textField.setText("");
				
				
                 
				/*String result = new TCPClient().send(msg);
				int row = Integer.parseInt(result) - 1;

				String str1 = table.getValueAt(row, 0).toString();
				String str2 = table.getValueAt(row, 1).toString();
				String str3 = table.getValueAt(row, 2).toString();
				String str4 = table.getValueAt(row, 3).toString();

				model.setRowCount(0);

				model.addRow(new String[] { str1, str2, str3, str4 });
				JTable table = new JTable(model);
				JScrollPane pane = new JScrollPane(table);
				panel.add(pane);*/
				

			}

		});

        
		JLabel label = new JLabel("当前购物车: "+totalCount+"件");
		label.setBounds(10, 10, 162, 15);
		contentPane.add(label);
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(true){
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
						// TODO: handle exception
					}
					label.setText("当前购物车："+totalCount+"件");
				}
			}
		}).start();
		
		JButton button_5 = new JButton("查看购物车");
		
		
		button_5.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				UserCartFrame usercart = new UserCartFrame(username);
				// 避免子，父选框连删
				usercart.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
				usercart.setVisible(true);
			}
		});
		button_5.setBounds(120, 6, 110, 23);
		contentPane.add(button_5);

		/*JButton AllGodsButton = new JButton("查询全部");
		AllGodsButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String total = "showAllGoods";
				String msg = "AllGoods###" + total;

				String result = new TCPClient().send(msg);

				if ("success".equals(result)) {

					model.setRowCount(0);
					File dir = new File("D:/store/goods");

					if (!dir.exists()) {
						dir.mkdirs();
					}

					int FileNum = dir.list().length;
					String path;
					Goods goods;

					if (FileNum != 0) {
						for (int i = 0; i < FileNum; i++) {

							path = "goods/" + (i + 1) + ".txt";
							goods = ObjectStream.read(Goods.class, path);
							model.addRow(new String[] { String.valueOf(goods.getGid()), goods.getGoodsName(),
									String.valueOf(goods.getPrice()), String.valueOf(goods.getAmount()) });

						}
					}

				}

			}
		});
		AllGodsButton.setBounds(304, 45, 93, 23);
		contentPane.add(AllGodsButton);*/
	}
}
